package sourceTools;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONObject;
import tools.URLDecode;

import com.bj58.analysis.tools.etl.bean.ETLTrackBean;




public class SourceEntry
{
	public static String qdStr = "xmgg,qq20130901,360mz,haouc,zm02,zmios,zm91,uc_jp_0220,uc_mz_0220,xmjp,360sh,baidu_tg,360fchz,360zpdh,360wls,360jp,baidu_rm,qq_pinche,hao123kz,hao123mz,headlinetoday,qq-gdtong,qqsymz,shoujitengxunwang,weidianpu,tianyiadapp";
	public static String seoStr = "baidu,google,soso,sogou,youdao,so,bing,yahoo,haosou";
	public static String[] seoOtherYuMingStr = { ".sm.cn", "ma.ucweb.com", ".easou.com" };
	public static String[] seoOtherYuMingVal = { "shenma", "ucweb", "easou" };
	public static String[] seoAddStr = { "baiduboxapp" };

	public List<String> sourceList = null;

	public SourceEntry(ETLTrackBean trackinfo, Map<String, String> sourceQDInfo, Map<String, String> sourceLMInfo, List<String> marketSpmList)
	{
		this.sourceList = getSourceList2(trackinfo, sourceQDInfo, sourceLMInfo, marketSpmList);
	}


	//2015-02-01之后
	public static List<String> getSourceList2(ETLTrackBean trackinfo,Map<String,String> sourceQDInfo,Map<String,String> sourceLMInfo,List<String> marketSpmList){
		//新的spm字典表
		HashMap<String,String> spmMap = new HashMap<String,String>();
	    for (String marktspm : marketSpmList) {
	      String[] strArr = marktspm.split("\t", -1);
	      if (strArr[2].equals("移动端") && strArr[0].indexOf("b-32948702282246-")==-1 && strArr[0].indexOf("b-12345678901234-")==-1) {
	        String spmKey = strArr[0] + "." + strArr[1];
	        String source2 = "";
	        if (strArr[3].equals("付费其他") || strArr[3].equals("付费其它"))
	          source2 = "fufeiqita";
	        else if (strArr[3].equals("付费浏览器"))
	          source2 = "fufeiliulanqi";
	        else if (strArr[3].equals("58系APP"))
	          source2 = "58系APP站点";
	        else if (strArr[3].equals("58系M"))
	          source2 = "58系M站点";
	        else {
	          source2 = strArr[3];
	        }
	        String spmVal = "qd\t" + source2 + "\t" + strArr[4] + "\t" + strArr[5];
	        spmMap.put(spmKey, spmVal);
	      }
	    }

	    List<String> sourceList = new ArrayList<String>();
	    sourceList.add("all");
	    String tkUrl = trackinfo.getUrl();
	    String tkReferrer = trackinfo.getReferrer();
	    String userAgent = trackinfo.getUserAgent();
	    String trackURL = trackinfo.getTrackUrl();
	    JSONObject jsonObj = JSONObject.fromObject(trackURL);

	    tkReferrer = URLDecode.urlDecode(tkReferrer);
	    userAgent = userAgent.toLowerCase();

		List<String> sourceLMList=new ArrayList<String>();
		sourceLMList.addAll(sourceLMInfo.keySet());
		Collections.sort(sourceLMList, new Comparator<String>() {
			public int compare(String a, String b) {
	              return b.compareTo(a);
	            }
	         });

		//专门为jxydt_app判断
	    if (tkReferrer.indexOf("utm_source=jxydt_app") != -1) {
	        String s1 = tkReferrer.split("utm_source=")[1];
	        int end = (s1.indexOf("&") != -1) ? s1.indexOf("&") : s1.length();
	        String s2 = s1.substring(0, end);
	        if (sourceQDInfo.get(s2) != null) {
	          sourceList.add("qd");
	          String[] sourceArrTemp = ((String)sourceQDInfo.get(s2)).split("\t");
	          for (int i = 0; (i < sourceArrTemp.length) && (i < 3) &&
	            (!("null".equals(sourceArrTemp[i]))); ++i)
	          {
	            if ("".equals(sourceArrTemp[i])) {
	              break;
	            }

	            sourceList.add(sourceArrTemp[i]);
	          }
	          return sourceList;
	        }

	      }

		//---------------20150608最新的切换成spm----------------
	    String strSpm = getParameters(tkUrl, "spm=");
	    if ((strSpm != null) && (spmMap.get(strSpm) != null))
	    {
	      String[] arrys = ((String)spmMap.get(strSpm)).split("\t");
	      for (String source : arrys) {
	        sourceList.add(source);
	      }
	      return sourceList;
	    }

//	    for (Map.Entry<String, String> entry : spmMap.entrySet()) {
//	    	String spmkey = entry.getKey();
//	    	String spmval = entry.getValue();
//	    	if(tkUrl.contains("spm="+spmkey)){
//	    	  String[] arrys = spmval.split("\t");
//	  	      for (String source : arrys) {
//	  	        sourceList.add(source);
//	  	      }
//	  	      return sourceList;
//	    	}
//	    }

		//0.联盟
	    for (String spm : sourceLMList) {
	    	if(trackURL.contains(String.format("'spm':'%s", spm)) || tkUrl.contains("spm="+spm)){
	          if ("手机QQ".equals(sourceLMInfo.get(spm))) {
	            sourceList.add("shoujiqq");
	          } else if ("momo".equals(sourceLMInfo.get(spm))) {
	            sourceList.add("momo");
	          } else {
	            sourceList.add("qd");
	            sourceList.add("lianmeng");
	            sourceList.add(sourceLMInfo.get(spm));
	          }
	          return sourceList;
	        }
	      }

		List<String> sourceQDList=new ArrayList<String>();
		sourceQDList.addAll(sourceQDInfo.keySet());
		Collections.sort(sourceQDList, new Comparator<String>() {
			public int compare(String a, String b) {
	              return b.compareTo(a);
	            }
	         });



		//1.渠道
		for (String qd : sourceQDList)
	    {
	      if ((tkReferrer.indexOf("utm_source=" + qd) != -1) || (trackURL.indexOf("'utm_source':'" + qd + "'") != -1) || (tkUrl.indexOf("utm_source=" + qd) != -1))
	      {
	        if (qd.equals("mzt_shouq_googzh")) {
	          sourceList.add("other");
	          sourceList.add("wei-手Q服务号");
	          return sourceList;
	        }
	        sourceList.add("qd");
	        String[] sourceArrTemp = ((String)sourceQDInfo.get(qd)).split("\t");
	        for (int i = 0; (i < sourceArrTemp.length) && (i < 3) &&
	          (!("null".equals(sourceArrTemp[i]))); ++i)
	        {
	          if ("".equals(sourceArrTemp[i])) {
	            break;
	          }

	          sourceList.add(sourceArrTemp[i]);
	        }
	        return sourceList;
	      }

	    }
		//2.1补充搜索信息
		for(String seo:seoAddStr)
		{
			if(userAgent.indexOf(seo)!=-1)
			{
				sourceList.add("sou");
				sourceList.add(seo);
				return sourceList;
			}
		}

		//2.2搜索引擎
		for(String seo:seoStr.split(","))
		{
			//搜索引擎
			if(tkReferrer.contains("."+ seo + ".com") )//&& tkUrl.contains(".58.com")
			{
				sourceList.add("sou");
				sourceList.add(seo);
				return sourceList;
			}
		}

		//2.3其他类型域名搜索引擎
		for(int i=0;i<seoOtherYuMingStr.length;i++)
		{
			String seo=seoOtherYuMingStr[i];
			if(tkReferrer.contains(seo) )
			{
				sourceList.add("sou");
				sourceList.add(seoOtherYuMingVal[i]);
				return sourceList;
			}
		}


		if(tkUrl.indexOf("http://w.58.com/poster/zp/") != -1){
			sourceList.add("other");
			sourceList.add("weizhaopin"); //微招聘
			return sourceList;
		}
		if(tkUrl.indexOf("http://w.58.com/wfc/detail/") != -1){
			sourceList.add("other");
			sourceList.add("weifangchan"); //微房产
			return sourceList;
		}
		if(tkUrl.indexOf("http://w.58.com/wzp/detailH5") != -1){
			sourceList.add("other");
			sourceList.add("weizhaopin"); //微招聘
			return sourceList;
		}
		if(trackURL.indexOf("'pagetype':'weidian'") != -1){
			sourceList.add("other");
			sourceList.add("weidian"); //微店铺
			return sourceList;
		}
		if(userAgent.indexOf("__weibo__") != -1)//__weibo__
		{
			sourceList.add("other");
			sourceList.add("weibo"); //微博
			return sourceList;
		}
		else if(userAgent.indexOf("micromessenger") != -1)//MicroMessenger
		{
			sourceList.add("other");
			sourceList.add("weixin"); //微信
			return sourceList;
		}
		if(tkUrl.indexOf("qq-pf-to") != -1)
		{
			sourceList.add("other");
			sourceList.add("qqclient"); //qq
			return sourceList;
		}

		//4.pcfront
		if((tkUrl.indexOf("pcfront") != -1 || tkReferrer.indexOf("pcfront") != -1 || tkUrl.indexOf("refrom=www") != -1 || tkReferrer.indexOf("refrom=www") != -1)&& (tkUrl.indexOf("m.58.com") != -1 || tkUrl.indexOf("wap.58.com") != -1))
		{
			sourceList.add("ziyou");
			sourceList.add("pcfront");
			return sourceList;
		}
		//5.直接输入
		if(  (tkReferrer==null || "".equals(tkReferrer) ) && tkUrl.indexOf("utm_source") == -1 && tkUrl.indexOf("refrom=www") == -1 && (tkUrl.indexOf("m.58.com") != -1 || tkUrl.indexOf("wap.58.com") != -1))
		{
			sourceList.add("ziyou");
			sourceList.add("direct");
			return sourceList;
		}
		//6.自有流量
		if( (StringUtils.isBlank(jsonObj.get("utm_source").toString()) || tkReferrer.indexOf("utm_source") == -1) && (tkReferrer.indexOf("m.58.com") != -1 || tkReferrer.indexOf("wap.58.com") != -1)&& (tkUrl.indexOf("m.58.com") != -1 || tkUrl.indexOf("wap.58.com") != -1) )
		{
			sourceList.add("ziyou");
			sourceList.add("58");
			return sourceList;
		}

		//其它
		sourceList.add("other");
		sourceList.add("other");
		return sourceList;

	}

	private static String getParameters(String strInfo, String strKey)
	  {
	    if ((strInfo.contains(strKey)) && (strInfo.indexOf(strKey) < strInfo.length() - strKey.length()))
	    {
	      String strValue = strInfo.split(strKey)[1].trim();
	      if ((strValue.contains("&")) && (!(strValue.endsWith("&"))))
	      {
	        return strValue.split("&")[0].trim();
	      }

	      return strValue;
	    }

	    return null;
	  }
}
